package com.ndood.gateway.app.security.authentication;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.ndood.common.base.util.RegexUtils;
import com.ndood.gateway.domain.account_center.entity.dto.AccountCenterAccountDto;
import com.ndood.gateway.domain.account_center.service.AccountCenterService;

import lombok.extern.slf4j.Slf4j;

/**
 * 自定义UserDetailsService
 * DaoAuthenticationProvider
 * https://www.jianshu.com/p/b0cc88574f5d
 */
@Transactional
@Component
@Slf4j
public class ApiUserDetailsService implements UserDetailsService {

	@Autowired
	private AccountCenterService accountCenterService;
	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		log.debug("Step1: 进行登录，表单登录用户名:" + username);

		AccountCenterAccountDto account = null;
		if (RegexUtils.checkEmail(username)) {
			// 查看是否存在未激活邮箱
			account = accountCenterService.getAccountByEmail(username);
			
		} else if (RegexUtils.checkMobile(username)) {
			account = accountCenterService.getAccountByMobile(username);
			
		} else {
			// 适用于rememeberMe的调用
			try {
				account = accountCenterService.getAccountById(Integer.parseInt(username));
			} catch (Exception e) {
				throw new BadCredentialsException("无效的收银账号!");
			}
			
		}

		if (account == null) {
			throw new BadCredentialsException("收银员不存在或已冻结，请联系管理员处理!");
		}

		return account;
	}

}
